package dbgroup02.dao.db2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import dbgroup02.bean.Flight;
import dbgroup02.dao.FlightDao;

public class FlightDB2Dao implements FlightDao {

	private JdbcTemplate jdbcTemplate;

	ParameterizedRowMapper<Flight> getFlightMapper = new ParameterizedRowMapper<Flight>() {
		@Override
		public Flight mapRow(ResultSet resultSet, int arg1) throws SQLException {
			Flight flight = new Flight();
			flight.setIdFlight(resultSet.getInt(1));
			flight.setIdFlightRoute(resultSet.getInt(2));
			flight.setIdPlane(resultSet.getInt(3));
			flight.setDepartureDate(resultSet.getDate(4));
			flight.setDepartureTime(resultSet.getTime(5));
			flight.setDuration(resultSet.getInt(6));
			flight.setEconomyPrice(resultSet.getString(7));
			flight.setBusinessPrice(resultSet.getString(8));
			flight.setFirstClassPrice(resultSet.getString(9));
			return flight;
		}
	};

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public Flight getFlight(int idFlight) {
		List<Flight> result = jdbcTemplate.query("SELECT * FROM "
				+ FlightDao.SCHEMA + ".FLIGHT WHERE FLIGHT_ID = ?",
				new Object[] { idFlight }, getFlightMapper);

		if (result.size() > 0)
			return result.get(0);
		else
			return null;
	}

}
